<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col id="btn0" :span="2">
                <el-button type="danger" @click="handleRejectBatch">批量暂停</el-button>
            </el-col>
            <el-col id="btn1" :span="2">
                <el-button type="success" @click="handleApproveBatch">批量激活</el-button>
            </el-col>
            <el-col :span="4">
                <el-select v-model="selectedType" placeholder="选择广告状态" @change="handleFilterChange"
                    class="filter-select">
                    <el-option label="所有状态" value=""></el-option>
                    <el-option label="激活中" value="激活中"></el-option>
                    <el-option label="暂停中" value="暂停中"></el-option>
                    <el-option label="已过期" value="已过期"></el-option>
                    <el-option label="待审核" value="待审核"></el-option>
                </el-select>
            </el-col>
            <el-col :offset="10" :span="4">
                <el-input v-model="searchName" placeholder="请输入广告名称" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedAdvertisements" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
                @sort-change="handleSortChange" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="30" />
                <el-table-column property='adId' label="广告ID" />
                <el-table-column property="adName" label="广告名称" />
                <el-table-column property="adOwner" label="广告主名称" />
                <el-table-column property="startDate" label="开始时间" sortable="custom" />
                <el-table-column property="endDate" label="结束时间" />
                <el-table-column property="targetUrl" label="目标链接" />
                <el-table-column property="adCost" label="广告费用" />
                <el-table-column property="adRevenue" label="广告收入" />
                <el-table-column property="clickNum" label="点击次数" />
                <el-table-column property="adStatus" label="广告状态" >
                <template #default="scope">
                    <span class="status-container">
                      <el-icon size="20">
                        <CircleCheck :class="getStatusIconClass(scope.row.adStatus)" />
                      </el-icon>
                      <span>{{scope.row.adStatus}}</span>
                    </span>
                  </template>
                </el-table-column>
                <!-- 操作按钮 -->success
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <!-- 激活 -->
                        <el-button type="success" @click="handleApproveApplication(row)"
                            :disabled="row.adStatus == '激活中'" link>
                            激活
                        </el-button>
                        <!-- 暂停 -->
                        <el-button type="danger" @click="handleRejectApplication(row)"
                            :disabled="row.adStatus !== '激活中'" link>
                            暂停
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);

// 定义选中的下拉框值
const selectedType = ref('');
//定义选中的行
const selectedRows = ref([]);
// 获取数据的函数
const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:8088/advertisements/filter', {
      params: {
        adStatus: selectedType.value,
      },
    });
    tableData.value = response.data.advertisements;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 处理下拉框变化的函数
const handleFilterChange = () => {
  fetchData();
};

const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/advertisements/getByPage', {
            params: {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
            },
        });
        tableData.value = response.data.records;
        total.value = response.data.total;
        pageNum.value = response.data.current;
        pageSize.value = response.data.size;
    } catch (error) {
        console.error('跳转失败:', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

//处理状态栏样式
function getStatusIconClass(adStatus: String) {
  switch (adStatus) {
    case "激活中":
      return 'status-icon-green';
    case "暂停中":
      return 'status-icon-red';
    case "已过期":
      return 'status-icon-gray';
    case "待审核":
        return 'status-icon-blue';
  }
}

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/advertisements/getByName', 
        { params: { adName: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateAdvertisementsStatus = async (adId, adStatus) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            adId,
            adStatus,
        };

        const response = await axios.put(
            "http://localhost:8088/advertisements/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("更新成功");// 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            const advertisements = tableData.value.find((item) => item.adId === adId);
            if (advertisements) {
                advertisements.adStatus = adStatus;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败");// 更新失败，给用户反馈
        return null;
    }
};


// 删除
const handleRejectApplication = (row) => {
    updateAdvertisementsStatus(row.adId, '暂停中'); 
};

// 通过审核
const handleApproveApplication = (row) => {
    updateAdvertisementsStatus(row.adId, '激活中'); 
};

// 组件挂载后获取初始数据
onMounted(() => {
    getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedAdvertisements = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'startDate') {
            const timeA = new Date(a.startDate).getTime();
            const timeB = new Date(b.startDate).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
};

const handleRejectBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要进行删除的帖子");;
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            adId: row.adId,
            adStatus: '暂停中',  // 固定为暂停中，或者根据需要动态赋值
        }));
        const response = await axios.put(
            "http://localhost:8088/advertisements/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            getData();
        }
        else {
            ElMessage.error("操作失败"); // 操作失败，给用户反馈
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};

const handleApproveBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要通过的帖子");
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            adId: row.adId,
            adStatus: '激活中',  
        }));
        const response = await axios.put(
            "http://localhost:8088/advertisements/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            getData();
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
    color: green;
    margin-right: 5px;
    /* 图标和文本之间的间距 */
  }
  
  .status-icon-red {
    color: red;
    margin-right: 5px;
  }
  
  .status-icon-gray {
    margin-right: 5px;
    color: gray;
  }

  .status-icon-blue {
    margin-right: 5px;
    color: blue;
  }

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>